/*
 * PruebaTabla.java
 *
 * Created on 28 de junio de 2007, 05:33 PM
 */

package everest3;


import java.awt.Component; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.util.EventObject;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import tablasYBasesdeDatos.JDBCAdapter;

/**
 *
 * @author  Administrador
 */
public class PruebaTabla extends javax.swing.JFrame {
    
    /** Creates new form PruebaTabla */
    public PruebaTabla() {
        initComponents();
        ajuste();
         dataBase = new JDBCAdapter(
            "jdbc:postgresql://localhost:5432/everest",
            "org.postgresql.Driver",
            "postgres",
            "root");
         setUpSportColumn(jTable1.getColumnModel().getColumn(1));
         
    }
    
    boolean codigoArea=false;
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(130, 130, 130)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(65, 65, 65)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
        
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void ajuste(){
      DefaultListSelectionModel modelo = new  DefaultListSelectionModel();  
      modelo.addListSelectionListener(new modeloSeleccion());
      modelo.setSelectionMode(modelo.SINGLE_SELECTION);
      jTable1.setSelectionModel(modelo);
      
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
         try
                {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                }
           catch (java.lang.Exception e )
                {}
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PruebaTabla().setVisible(true);
            }
        });
    }
    private void validaDatos()
    {
        DefaultTableModel modeloTabla = (DefaultTableModel) jTable1.getModel();
        modeloTabla.addRow(new Object[]{
              "", "", "","" });
        
    }
    ComboBox1 codArea;
     public void setUpSportColumn(TableColumn sportColumn) {
        //Set up the editor for the sport cells.
         
      codArea =  new ComboBox1(dataBase.consultaCampos("select distinct areacodigo from materialbibliografico"));
       
        sportColumn.setCellEditor(new DefaultCellEditor(codArea));

        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);

        //Set up tool tip for the sport column header.
        TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
        if (headerRenderer instanceof DefaultTableCellRenderer) {
            ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
                     "Click the sport to see a list of choices");
        } 
    }
      public void setUpSportColumn2(TableColumn sportColumn, Object valor) {
        //Set up the editor for the sport cells.
         codigoArea=true;
      ComboBox1  consec =  new ComboBox1(dataBase.consultaCampos("select matcons from materialbibliografico "
                    +"where areacodigo = "+valor
            +" and matdsp=true"));
       
        sportColumn.setCellEditor(new DefaultCellEditor(consec));

        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);

        //Set up tool tip for the sport column header.
        TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
        if (headerRenderer instanceof DefaultTableCellRenderer) {
            ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
                     "Click the sport to see a list of choices");
        } 
    }

 public void cargarInfoMaterial(String codArea, String conse, int fila){
         
        if(codArea.equals(null)||(codArea==null)||(codArea==""))
            javax.swing.JOptionPane.showMessageDialog(this,"Campos Vacios");
        else{
                   
            Vector nombre = dataBase.ConsultaIndividual("select matnom from materialbibliografico where areacodigo = "+codArea+ "and matcons= "+conse+" and matdsp=true");
                    
       
                
         try{
             System.out.println(nombre.size());
              if(nombre.size()>0){
                 String valor=""+nombre.get(0);
                jTable1.setValueAt(valor,fila,3 );
            } 
              
         }
         catch (java.lang.NullPointerException e){
             jTable1.setValueAt("",fila,3 );
         }
        
         }    
     }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
      JDBCAdapter dataBase;
 class modeloSeleccion implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
       int ultimo= e.getLastIndex();
       int primero= e.getFirstIndex();
       jLabel1.setText("cambio de seleccion "+jTable1.getSelectedRow());
    }
     

   }


public class ComboBox1 extends JComboBox implements TableCellEditor, CaretListener {

   protected  int elementos=0;
    
  protected EventListenerList listenerList = new EventListenerList();

  protected ChangeEvent changeEvent = new ChangeEvent(this);

  private MyComboUI comboUi = new MyComboUI();

  private JTextField tf;
  public boolean seleccion=false;

  Object newValue;
    
    public ComboBox1(Vector vector){    
        super();
        elementos=vector.size();
        removeAllItems();
         setUI(comboUi);
        
        
         if (vector.size()>0){
             DecimalFormat df1 = new DecimalFormat("000");
            for(int i=0; i<vector.size(); i++)
                addItem(df1.format(vector.elementAt(i)));
        }         
        
        
        setEditable(true);
          tf = (JTextField) getEditor().getEditorComponent();
        tf.addCaretListener(this);
    

    tf.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == e.VK_ENTER) {
          Object value = comboUi.getList().getSelectedValue();
          tf.transferFocus();
          hidePopup();
          System.out.println("enter pressed, selected value, when enter pressed: " + value);
          seleccion=true;
          fireEditingStopped();
        }
      }
    });

    addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        // fireEditingStopped();
      }
    });
    }
    /**
     * Este metodo recibe los elementos a insertar en el combo box que en este caso son numeros
     * y les aplica un formato de numero de tres digitos 000
     * @param vector vector que contiene la informacion a insertar en el combo box
     */
    public void cargarDatos(Vector vector){   
        elementos=vector.size();
        if (vector.size()>0){
             DecimalFormat df1 = new DecimalFormat("000");
            for(int i=0; i<vector.size(); i++)
                addItem(df1.format(vector.elementAt(i)));
        }         
    }

  public int getNumeroElementos(){
      return elementos;
  }
  public void addCellEditorListener(CellEditorListener listener) {
    listenerList.add(CellEditorListener.class, listener);
  }

  public void removeCellEditorListener(CellEditorListener listener) {
    listenerList.remove(CellEditorListener.class, listener);
  }

  protected void fireEditingStopped() {
    System.out.println("fireEditingStopped called ");

    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
      if (listeners[i] == CellEditorListener.class) {
        listener = (CellEditorListener) listeners[i + 1];
        listener.editingStopped(changeEvent);
      }
    }
  }

  protected void fireEditingCanceled() {
    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
      //if (listeners == CellEditorListener.class) {
      if (listeners[i] == CellEditorListener.class) {
        listener = (CellEditorListener) listeners[i + 1];
        listener.editingCanceled(changeEvent);
      }
    }
  }

  public void cancelCellEditing() {
    System.out.println("cancelCellEditing called ");
    fireEditingCanceled();
  }

  public boolean stopCellEditing() {
    System.out.println("stopCellEditing called ");
    fireEditingStopped();
    return true;
  }

  public boolean isCellEditable(EventObject event) {
    return true;
  }

  public boolean shouldSelectCell(EventObject event) {
    return true;
  }

  public Object getCellEditorValue() {
    System.out.println("getCellEditorValue called returning vlaue: " + newValue);
   try{
       tf.setText(newValue.toString());
   }
   catch(java.lang.Exception e){
       javax.swing.JOptionPane.showMessageDialog(this,"el libro no existe o se encuentra prestado\n"+e);
   }
    seleccion=true;   
    return newValue;
    // return super.getSelectedItem();
  }

  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
      int row, int column) {

    return this;
  }

  public void caretUpdate(CaretEvent e) {
    if (!isPopupVisible() && tf.isShowing() && tf.hasFocus())
      showPopup();

    JTextField tf = (JTextField) e.getSource();
    String text = tf.getText().toLowerCase();

    int index = -1;
    for (int i = 0; i < super.getItemCount(); i++) {
      String item = ((String) getItemAt(i)).toLowerCase();
      if (item.startsWith(text)) {
        index = i;
        break;
      }
    }
    if (index != -1)
      comboUi.getList().setSelectedIndex(index);
    else
      comboUi.getList().clearSelection();

    newValue = comboUi.getList().getSelectedValue();
    System.out.println("new value set to: " + newValue);
   
    if(!codigoArea)
         setUpSportColumn2(jTable1.getColumnModel().getColumn(2), newValue);
    else
    {
        cargarInfoMaterial(codArea.getSelectedItem().toString(),newValue.toString(),jTable1.getSelectedRow());
    }
   
    seleccion=true;
  }    
    
}

class MyComboUI extends BasicComboBoxUI {

  public JList getList() {
    return listBox;
  }
}

 }
